<?php

namespace business\elasticsearch\services;

use business\elasticsearch\models\BigDataCustomerModel;
use business\base\services\HighFrequencyWordService;
use yii\elasticsearch\Command;

class BigDataCustomerService
{
    public function queryCustomerList(
        $keyword,
        $companyNameKeyword,
        $companyIdentity,
        $companyArea,
        $companyLevel,
        $companyLabel,
        $companyType,
        $industryCategory,
        $landUsageLabels,
        $fitmentFeeLabel,
        $projectTypeLabel,
        $biddingArea,
        $creditLevel,
        $projectProvinceCode, $projectCityCode, $projectDateMin, $projectDateMax,
        $page,
        $pageSize
    )
    {
        $condition = $this->buildQueryCustomerCondition(
            $keyword,
            $companyNameKeyword,
            $companyIdentity,
            $companyArea,
            $companyLevel,
            $companyLabel,
            $companyType,
            $industryCategory,
            $landUsageLabels,
            $fitmentFeeLabel,
            $projectTypeLabel,
            $biddingArea,
            $creditLevel,
            $projectProvinceCode, $projectCityCode, $projectDateMin, $projectDateMax
        );
        if (empty($condition)) {
            return ['total' => 0, 'list' => []];
        }
//        echo json_encode($condition, 256);
//        exit;
        $query = BigDataCustomerModel::find()->query($condition);
        //高亮处理 得处理两个部分，一个是模糊搜索，一个是列表
        $highlight = [
            'pre_tags' => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields" => [
                "company_name" => new \stdClass(),
                "company_name.keyword" => new \stdClass(),
                "old_name_arr.name" => new \stdClass(),
                "project_arr.project_name" => new \stdClass(),
            ]
        ];
        //todo 指定查询字段，无需返回页面不展示的字段
        $field = [
            "organizing_code", "company_name", "top_company_name", "top_company_organizing_code", "company_type", "enterprise_nature",
            "short_name", "old_name_arr", "is_supplier", "is_developer", "developer_id", "developer_logo",
            "customer_dynamic_arr", "province", "city", "province_code", "city_code", "business_status_label", "contact_num",
            "cooperation_case_cnt_1year", "sell_project_cnt_1year", "commence_permit_cnt_1year", "take_land_cnt_1year", "bid_cnt_1year",
            "cooperation_case_cnt_2year", "sell_project_cnt_2year", "commence_permit_cnt_2year", "take_land_cnt_2year", "bid_cnt_2year",
            "regist_capi", "regist_capi_unit", "legal_name", "establish_date", "credit_level_label",
            "industry_category_big", "industry_category_middle", "industry_category_small",
            "company_label_arr", "company_level_arr", "land_usage_label_arr",
            "purchase_demand_cnt_2year_with_area_arr", "land_cnt_2year_with_area_arr", "commence_permit_cnt_2year_with_area_arr",
            "sell_project_cnt_2year_with_area_arr", "cooperation_case_cnt_2year_with_area_arr",
        ];
        $query->source($field);
        $query->highlight($highlight);
        $query->orderBy(['_score' => SORT_DESC, "_id" => SORT_DESC]);

        //分页处理
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $searchData = $query->createCommand()->search();

        $total = 0;
        $list = [];
        if (!empty($searchData)) {
            $data = $searchData["hits"]["hits"];
            $total = $searchData["hits"]["total"];
            foreach ($data as $dv) {
                $tmp = $dv['_source'];
                if (isset($tmp["land_data_arr"])) {
                    unset($tmp["land_data_arr"]);
                }
                if (isset($tmp["project_data_arr"])) {
                    unset($tmp["project_data_arr"]);
                }
                if (isset($dv['highlight']) && is_array($dv['highlight'])) {
                    foreach ($dv['highlight'] as $key => $value) {
                        $tmp[$key . 'HL'] = $value[0] ?? '';
                    }
                }
                // 如果 company_name.keyword 匹配到了，且其他条件没有匹配到，就高亮这个
                if (empty($tmp["company_nameHL"]) && !empty($tmp["company_name.keywordHL"])) {
                    $tmp["company_nameHL"] = $tmp["company_name.keywordHL"];
                    unset($tmp["company_name.keywordHL"]);
                }

                // 如果项目地区不为空，那么根据项目地区，取区域内的拿地、开盘、合作案例、开工、招标指标
                $tmp = $this->getInAreaProjectMetrics($tmp, $projectProvinceCode, $projectCityCode);
                $tmp['_score'] = $dv['_score'];
                $list[] = $tmp;
            }
        }
        return ['total' => $total, 'list' => $list];
    }

    private function getInAreaProjectMetrics($customerInfo, $projectProvinceCode, $projectCityCode): array
    {
        $result = [
            "bid_cnt_with_area_2year" => 0,
            "land_cnt_with_area_2year" => 0,
            "commence_permit_cnt_with_area_2year" => 0,
            "sell_project_with_cnt_area_2year" => 0,
            "cooperation_case_cnt_with_area_2year" => 0,
        ];
        if (!empty($projectCityCode)) {
            //招标
            if (isset($customerInfo["purchase_demand_cnt_2year_with_area_arr"]) && $customerInfo["purchase_demand_cnt_2year_with_area_arr"] != "") {
                $bidMetrics = json_decode($customerInfo["purchase_demand_cnt_2year_with_area_arr"], true);
                if (is_array($bidMetrics) && !empty($bidMetrics)) {
                    foreach ($bidMetrics as $item) {
                        if (sizeof($item) >= 3) {
//                            $provinceCode = $item[0] ?? "";
                            $cityCode = $item[1] ?? "";
                            $prjCount = $item[2] ?? 0;
                            if ($cityCode == $projectCityCode) {
                                $result["bid_cnt_with_area_2year"] = $prjCount;
                                break;
                            }
                        }
                    }
                }
                unset($customerInfo["purchase_demand_cnt_2year_with_area_arr"]);
            }
            //拿地
            if (isset($customerInfo["land_cnt_2year_with_area_arr"]) && $customerInfo["land_cnt_2year_with_area_arr"] != "") {
                $landMetrics = json_decode($customerInfo["land_cnt_2year_with_area_arr"], true);
                if (is_array($landMetrics) && !empty($landMetrics)) {
                    foreach ($landMetrics as $item) {
                        if (sizeof($item) >= 3) {
//                            $provinceCode = $item[0] ?? "";
                            $cityCode = $item[1] ?? "";
                            $prjCount = $item[2] ?? 0;
                            if ($cityCode == $projectCityCode) {
                                $result["land_cnt_with_area_2year"] = $prjCount;
                                break;
                            }
                        }
                    }
                }
                unset($customerInfo["land_cnt_2year_with_area_arr"]);
            }
            //在建
            if (isset($customerInfo["commence_permit_cnt_2year_with_area_arr"]) && $customerInfo["commence_permit_cnt_2year_with_area_arr"] != "") {
                $commenceMetrics = json_decode($customerInfo["commence_permit_cnt_2year_with_area_arr"], true);
                if (is_array($commenceMetrics) && !empty($commenceMetrics)) {
                    foreach ($commenceMetrics as $item) {
                        if (sizeof($item) >= 3) {
//                            $provinceCode = $item[0] ?? "";
                            $cityCode = $item[1] ?? "";
                            $prjCount = $item[2] ?? 0;
                            if ($cityCode == $projectCityCode) {
                                $result["commence_permit_cnt_with_area_2year"] = $prjCount;
                                break;
                            }
                        }
                    }
                }
                unset($customerInfo["commence_permit_cnt_2year_with_area_arr"]);
            }
            //开盘
            if (isset($customerInfo["sell_project_cnt_2year_with_area_arr"]) && $customerInfo["sell_project_cnt_2year_with_area_arr"] != "") {
                $saleMetrics = json_decode($customerInfo["sell_project_cnt_2year_with_area_arr"], true);
                if (is_array($saleMetrics) && !empty($saleMetrics)) {
                    foreach ($saleMetrics as $item) {
                        if (sizeof($item) >= 3) {
//                            $provinceCode = $item[0] ?? "";
                            $cityCode = $item[1] ?? "";
                            $prjCount = $item[2] ?? 0;
                            if ($cityCode == $projectCityCode) {
                                $result["sell_project_with_cnt_area_2year"] = $prjCount;
                                break;
                            }
                        }
                    }
                }
                unset($customerInfo["sell_project_cnt_2year_with_area_arr"]);
            }
            //合作案例
            if (isset($customerInfo["cooperation_case_cnt_2year_with_area_arr"]) && $customerInfo["cooperation_case_cnt_2year_with_area_arr"] != "") {
                $cooperationMetrics = json_decode($customerInfo["cooperation_case_cnt_2year_with_area_arr"], true);
                if (is_array($cooperationMetrics) && !empty($cooperationMetrics)) {
                    foreach ($cooperationMetrics as $item) {
                        if (sizeof($item) >= 3) {
//                            $provinceCode = $item[0] ?? "";
                            $cityCode = $item[1] ?? "";
                            $prjCount = $item[2] ?? 0;
                            if ($cityCode == $projectCityCode) {
                                $result["cooperation_case_cnt_with_area_2year"] = $prjCount;
                                break;
                            }
                        }
                    }
                }
                unset($customerInfo["cooperation_case_cnt_2year_with_area_arr"]);
            }
        } elseif (!empty($projectProvinceCode)) {
            //招标
            if (isset($customerInfo["purchase_demand_cnt_2year_with_area_arr"]) && $customerInfo["purchase_demand_cnt_2year_with_area_arr"] != "") {
                $bidMetrics = json_decode($customerInfo["purchase_demand_cnt_2year_with_area_arr"], true);
                if (is_array($bidMetrics) && !empty($bidMetrics)) {
                    foreach ($bidMetrics as $item) {
                        if (sizeof($item) >= 3) {
                            $provinceCode = $item[0] ?? "";
//                            $cityCode = $item[1] ?? "";
                            $prjCount = $item[2] ?? 0;
                            if ($provinceCode == $projectProvinceCode) {
                                $result["bid_cnt_with_area_2year"] += $prjCount;
                            }
                        }
                    }
                }
                unset($customerInfo["purchase_demand_cnt_2year_with_area_arr"]);
            }
            //拿地
            if (isset($customerInfo["land_cnt_2year_with_area_arr"]) && $customerInfo["land_cnt_2year_with_area_arr"] != "") {
                $landMetrics = json_decode($customerInfo["land_cnt_2year_with_area_arr"], true);
                if (is_array($landMetrics) && !empty($landMetrics)) {
                    foreach ($landMetrics as $item) {
                        if (sizeof($item) >= 3) {
                            $provinceCode = $item[0] ?? "";
//                            $cityCode = $item[1] ?? "";
                            $prjCount = $item[2] ?? 0;
                            if ($provinceCode == $projectProvinceCode) {
                                $result["land_cnt_with_area_2year"] += $prjCount;
                            }
                        }
                    }
                }
                unset($customerInfo["land_cnt_2year_with_area_arr"]);
            }
            //在建
            if (isset($customerInfo["commence_permit_cnt_2year_with_area_arr"]) && $customerInfo["commence_permit_cnt_2year_with_area_arr"] != "") {
                $commenceMetrics = json_decode($customerInfo["commence_permit_cnt_2year_with_area_arr"], true);
                if (is_array($commenceMetrics) && !empty($commenceMetrics)) {
                    foreach ($commenceMetrics as $item) {
                        if (sizeof($item) >= 3) {
                            $provinceCode = $item[0] ?? "";
//                            $cityCode = $item[1] ?? "";
                            $prjCount = $item[2] ?? 0;
                            if ($provinceCode == $projectProvinceCode) {
                                $result["commence_permit_cnt_with_area_2year"] += $prjCount;
                            }
                        }
                    }
                }
                unset($customerInfo["commence_permit_cnt_2year_with_area_arr"]);
            }
            //开盘
            if (isset($customerInfo["sell_project_cnt_2year_with_area_arr"]) && $customerInfo["sell_project_cnt_2year_with_area_arr"] != "") {
                $saleMetrics = json_decode($customerInfo["sell_project_cnt_2year_with_area_arr"], true);
                if (is_array($saleMetrics) && !empty($saleMetrics)) {
                    foreach ($saleMetrics as $item) {
                        if (sizeof($item) >= 3) {
                            $provinceCode = $item[0] ?? "";
//                            $cityCode = $item[1] ?? "";
                            $prjCount = $item[2] ?? 0;
                            if ($provinceCode == $projectProvinceCode) {
                                $result["sell_project_with_cnt_area_2year"] += $prjCount;
                            }
                        }
                    }
                }
                unset($customerInfo["sell_project_cnt_2year_with_area_arr"]);
            }
            //合作案例
            if (isset($customerInfo["cooperation_case_cnt_2year_with_area_arr"]) && $customerInfo["cooperation_case_cnt_2year_with_area_arr"] != "") {
                $cooperationMetrics = json_decode($customerInfo["cooperation_case_cnt_2year_with_area_arr"], true);
                if (is_array($cooperationMetrics) && !empty($cooperationMetrics)) {
                    foreach ($cooperationMetrics as $item) {
                        if (sizeof($item) >= 3) {
                            $provinceCode = $item[0] ?? "";
//                            $cityCode = $item[1] ?? "";
                            $prjCount = $item[2] ?? 0;
                            if ($provinceCode == $projectProvinceCode) {
                                $result["cooperation_case_cnt_with_area_2year"] += $prjCount;
                            }
                        }
                    }
                }
                unset($customerInfo["cooperation_case_cnt_2year_with_area_arr"]);
            }
        }

        return array_merge($customerInfo, $result);
    }

    private function buildQueryCustomerCondition(
        $keyword,
        $companyNameKeyword,
        $companyIdentity = [],
        $companyArea = [],
        $companyLevel = [],
        $companyLabel = [],
        $companyType = [],
        $industryCategory = [],
        $landUsageLabel = [],
        $fitmentFeeLabel = [],
        $projectTypeLabel = [],
        $biddingArea = [],
        $creditLevel = [],
        $projectProvinceCode = '', $projectCityCode = '',
        $projectDateMin = '', $projectDateMax = ''
    ): array
    {
        $must = [];
        // 搜索条件
        // 关键词匹配公司名称、简称、曾用名、合作案例标题
        // and 公司类型 in companyIdentity and 公司注册地址 in companyArea and 企业等级 in companyLevel
        // and 企业标签 in companyLabel and 企业类型 in companyType and 三级行业 in industryCategory
        // and 土地用途 in landUsageLabel and 工程用途 in buildingTypes and 装修类型 in fitmentFeeLabel
        // and 项目地区 in projectArea
        //
        $level1 = 500;
        $level2 = 200;
        $level3 = 100;
        $level4 = 50;
        $level5 = 10;
        if ($keyword != "") {
            $keywordCondition = [];
            $keywordCondition[] = [
                'match' => ['company_name.keyword' => ["query" => $keyword, "boost" => $level1]]
            ];
            $slop = !empty(\Yii::$app->params['CommonDataDeveloperSlop']) ? \Yii::$app->params['CommonDataDeveloperSlop'] : 2;
            $keywordCondition[] = [
                'match_phrase' => ['company_name' => ["query" => $keyword, "boost" => $level2, 'slop' => $slop]]
            ];
            // 实现类似 sql like 查询 keyword %
            $keywordCondition[] = ['match_phrase_prefix' => ['company_name.keyword' => ["query" => $keyword]]];
            //简称
            $keywordCondition[] = ['match' => ['short_name' => ["query" => $keyword, "boost" => $level4]]];
            //曾用名
            $keywordCondition[] = ["nested" => ["path" => "old_name_arr", "query" => ["match_phrase" => ["old_name_arr.name" => ["query" => $keyword, "boost" => $level4, 'slop' => $slop]]]]];
            $keywordCondition[] = ["nested" => ["path" => "old_name_arr", "query" => ["match" => ["old_name_arr.name.keyword" => ["query" => $keyword, "boost" => $level3]]]]];
            //合作案例标题，合作案例只有合作单位有数据，且只取了前20条
            $keywordCondition[] = ["nested" => ["path" => "project_arr", "query" => ["match_phrase" => ["project_arr.project_name" => ["query" => $keyword, "boost" => $level5, 'slop' => $slop]]]]];
//            $subWords = $this->getAnalyze($keyword);
//            if (!empty($subWords)) {
//                foreach ($subWords as $val) {
//                    $keywordCondition[] = [
//                        'match_phrase' => ['company_name' => ["query" => $val, "boost" => $level5]]
//                    ];
//                    $keywordCondition[] = ['match' => ['short_name' => ["query" => $val, "boost" => $level5]]];
//                    //曾用名
//                    $keywordCondition[] = ["nested" => ["path" => "old_name_arr", "query" => ["match_phrase" => ["old_name_arr.name" => ["query" => $val, "boost" => 50, 'slop' => $slop]]]]];
//                    $keywordCondition[] = ["nested" => ["path" => "old_name_arr", "query" => ["match" => ["old_name_arr.name.keyword" => ["query" => $val, "boost" => 100]]]]];
//                    //合作案例标题，合作案例只有合作单位有数据，且只取了前20条
//                    $keywordCondition[] = ["nested" => ["path" => "project_arr", "query" => ["match_phrase" => ["project_arr.project_name" => ["query" => $val, "boost" => 50, 'slop' => $slop]]]]];
//                }
//            }
            $must[] = ["bool" => ["should" => $keywordCondition]];
        } elseif ($companyNameKeyword != "") {
            // 只匹配公司名称
            // 业务测应用场景:在省市洞察的企业维度列表中用到
            $keywordCondition = [];
            $keywordCondition[] = [
                'match' => ['company_name.keyword' => ["query" => $companyNameKeyword, "boost" => $level1]]
            ];
            $slop = !empty(\Yii::$app->params['CommonDataDeveloperSlop']) ? \Yii::$app->params['CommonDataDeveloperSlop'] : 2;
            $keywordCondition[] = [
                'match_phrase' => ['company_name' => ["query" => $companyNameKeyword, "boost" => $level2, 'slop' => $slop]]
            ];
            // 实现类似 sql like 查询 keyword %
            $keywordCondition[] = ['match_phrase_prefix' => ['company_name.keyword' => ["query" => $companyNameKeyword]]];
            $must[] = ["bool" => ["should" => $keywordCondition]];
        }

        if (!empty($companyArea)) {
            $must[] = ["bool" => ["should" => [["terms" => ["city_code" => $companyArea]], ["terms" => ["province_code" => $companyArea]]]]];
        }

        // 当同时查询甲方单位或上下游单位时，等同于没有这个搜索条件
        if (!empty($companyIdentity) && sizeof($companyIdentity) == 1) {
            foreach ($companyIdentity as $item) {
                if ($item === "甲方单位") {
                    $must[] = ["term" => ["is_developer" => 1]];
                }
                if ($item === "上下游单位") {
                    $must[] = ["term" => ["is_supplier" => 1]];
                }
            }
        }

        if (!empty($companyLevel)) {
            $must[] = ["nested" => ["path" => "company_level_arr", "query" => ["terms" => ["company_level_arr.name" => $companyLevel]]]];
        }

        if (!empty($companyLabel)) {
            $must[] = ["nested" => ["path" => "company_label_arr", "query" => ["terms" => ["company_label_arr.name" => $companyLabel]]]];
        }

        if (!empty($companyType)) {
            $must[] = ["terms" => ["company_type" => $companyType]];
        }

        if (!empty($industryCategory)) {
            $must[] = ["terms" => ["industry_category_small" => $industryCategory]];
        }

        if (!empty($landUsageLabel)) {
            $must[] = ["nested" => ["path" => "land_usage_label_arr", "query" => ["terms" => ["land_usage_label_arr.name" => $landUsageLabel]]]];
        }

        if (!empty($fitmentFeeLabel)) {
            $must[] = ["nested" => ["path" => "fitment_fee_label_arr", "query" => ["terms" => ["fitment_fee_label_arr.name" => $fitmentFeeLabel]]]];
        }

        if (!empty($projectTypeLabel)) {
            $must[] = ["nested" => ["path" => "project_type_label_arr", "query" => ["terms" => ["project_type_label_arr.name" => $projectTypeLabel]]]];
        }

        if (!empty($biddingArea)) {
            $must[] = ["nested" => ["path" => "project_arr", "query" => ["bool" => ["should" => [["terms" => ["project_arr.city_code" => $biddingArea]], ["terms" => ["project_arr.province_code" => $biddingArea]]]]]]];
        }

        // 项目地区匹配
        if (!empty($projectProvinceCode) || !empty($projectCityCode)) {
            $projectArea = [];
            if (!empty($projectProvinceCode)) {
                $projectArea[] = $projectProvinceCode;
            }
            if (!empty($projectCityCode)) {
                $projectArea[] = $projectCityCode;
            }
            $must[] = ["nested" => ["path" => "project_area_code_3year_arr", "query" => ["terms" => ["project_area_code_3year_arr.area_code" => $projectArea]]]];
        }

        if (!empty($projectDateMin) && !empty($projectDateMax)) {
            $must[] = ["nested" => ["path" => "project_date_3year_arr", "query" => ["range" => ["project_date_3year_arr.date" => ["from" => $projectDateMin, "to" => $projectDateMax]]]]];
        }

        if (!empty($creditLevel)) {
            $must[] = ["terms" => ["credit_level_label" => $creditLevel]];
        }

        $query['function_score']['query']['bool']['must'] = $must;
        // 排序权重,权重值已清洗至business_score字段
        //近一年招标:超过20条，+200分;11-20条，+150分;6-10条，+100分;1-5条，+50; bid_cnt_1year
        //近一年有拿地数量:超过10块，+200分;6-10块，+150分;2-5块，+100分;1块，+50; take_land_cnt_1year
        //近一年开盘数据:超过10块，+200分;6-10块，+150分;2-5块，+100分;1块，+50; sell_project_cnt_1year
        //近一年在建项目数据:超过10块，+200分;6-10块，+150分;2-5块，+100分;1块，+50; commence_permit_cnt_1year
        //近一年合作案例数据:超过10个，+200分;6-10个，+150分;2-5个，+100分;1个，+50; cooperation_case_cnt_1year
        //权重排序
        $query['function_score']['functions'] = [
            ['script_score' => ['script' => "doc['business_score'].value"]],
        ];
        $query['function_score']['score_mode'] = 'sum';
        $query['function_score']['boost_mode'] = 'sum';

        return $query;
    }

    public function getCustomerDetail($organizingCodes)
    {
        $condition = $this->buildQueryDetailCondition($organizingCodes);
        if (empty($condition)) {
            return ['total' => 0, 'list' => []];
        }

        $searchData = BigDataCustomerModel::find()->query($condition)->createCommand()->search();
        $result = [];
        if (!empty($searchData) && isset($searchData["hits"]) &&
            isset($searchData["hits"]["hits"])) {
            foreach ($searchData["hits"]["hits"] as $item) {
                if (isset($item["_source"])) {
                    $result[] = $item["_source"];
                }
            }
        }
        return $result;
    }

    private function buildQueryDetailCondition($organizingCodes): array
    {
        return ["terms" => ["_id" => $organizingCodes]];
    }

    public function guessName($keyword, $pageSize): array
    {
        $condition = $this->buildQueryCustomerCondition($keyword);
        $query = BigDataCustomerModel::find()
            ->query($condition);
        //高亮处理
        $highlight = [
            'pre_tags' => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields" => [
                "company_name" => new \stdClass(),
                "company_name.keyword" => new \stdClass(),
                "old_name_arr.name" => new \stdClass(),
                "project_arr.project_name" => new \stdClass(),
            ]
        ];
        $query->highlight($highlight);
        $query->orderBy(['_score' => SORT_DESC]);

        //分页处理
        $query->limit($pageSize);
        $searchData = $query->createCommand()->search();
        //数据处理
        $result = [];
        if (!empty($searchData)) {
            $data = $searchData["hits"]["hits"];
//            echo json_encode($data, 256);
//            exit;
            foreach ($data as $dv) {
                $tmp = $dv['_source'];
                if (isset($dv['highlight']) && is_array($dv['highlight'])) {
                    foreach ($dv['highlight'] as $key => $value) {
                        $tmp[$key . 'HL'] = $value[0] ?? '';
                    }
                }
                $item["company_name"] = $tmp["company_name"];
                $item["company_nameHL"] = $tmp["company_nameHL"] ?? "";
                $item["old_company_nameHL"] = $tmp["old_name_arr.nameHL"] ?? "";
                // 如果 company_name.keyword 匹配到了，且其他条件没有匹配到，就高亮这个
                if (empty($item["company_nameHL"]) && !empty($tmp["company_name.keywordHL"])) {
                    $item["company_nameHL"] = $tmp["company_name.keywordHL"];
                }
                $result[] = $item;
            }
        }
        return $result;
    }

    public function getDeveloperScore($organizingCodes = [], $subscription = []): array
    {
        //通过社会信用代码取查询采购商主档案
        $condition = ["function_score" => ["query" => ['terms' => ['organizing_code' => $organizingCodes]]]];
        $query = BigDataCustomerModel::find()
            ->query($condition);
        $query->limit(count($organizingCodes));
        //$data = $query->asArray()->all();
        $searchData = $query->createCommand()->search();

        $result = [];
        if (!empty($searchData)) {
            $data = $searchData["hits"]["hits"];
            foreach ($data as $dv) {
                $src = $dv['_source'];
                $developerScoreInfo = $this->getDeveloperScoreInfo($src, $subscription);
                $item = ["organizing_code" => $src["organizing_code"] ?? ""];
                $item['developer_score'] = $developerScoreInfo['developer_score'] ? intval($developerScoreInfo['developer_score']) : 0;
                $item['match_requirement_module_score'] = $developerScoreInfo['match_requirement_module_score'] ? intval($developerScoreInfo['match_requirement_module_score']) : 0;
                $item['match_requirement_land_ctn'] = $developerScoreInfo['match_requirement_land_ctn'] ?? 0;
                $item['match_requirement_project_ctn'] = $developerScoreInfo['match_requirement_project_ctn'] ?? 0;
                $result[] = $item;
            }
        }

        return $result;
    }

    // 获取开发商评分(好客户模型评分)
    private function getDeveloperScoreInfo($data, $subscription)
    {
        $landDataArr = $data['land_data_arr'] ?? [];
        $projectDataArr = $data['project_data_arr'] ?? [];
        $subscriptionLandUsageList = $subscription['land_usage_list'] ?? [];
        $subscriptionProjectTypeList = $subscription['project_type_list'] ?? [];

        $investModuleScore = $data['invest_module_score'] ?? 0;
        $recoveriesModuleScore = $data['recoveries_module_score'] ?? 0;
        $creditModuleScore = $data['credit_module_score'] ?? 0;
        $annualIncreaseModuleScore = $data['annual_increase_module_score'] ?? 0;

        $land_ctn = 0;
        $land_price = 0;
        //匹配需求-拿地
        foreach ($landDataArr as $item) {
            foreach ($item['land_usage_list'] as $landUsage) {
                // 用户订阅设置了【土地用途】：只匹配相同的【土地用途】的地块
                // 用户订阅没有设置【土地用途】：匹配所有的地块
                if (in_array($landUsage['name'], $subscriptionLandUsageList) || count($subscriptionLandUsageList) == 0) {
                    $land_ctn += 1;
                    $land_price += $item['price'];
                    break;
                }
            }
        }


        $project_ctn = 0;
        $project_price = 0;
        //匹配需求-在建项目
        foreach ($projectDataArr as $item) {
            // 用户订阅设置了【在建类型】：只匹配相同的【在建类型】的项目
            // 用户订阅没有设置【在建类型】：匹配所有的项目
            if (in_array($item['prj_type'], $subscriptionProjectTypeList) || count($subscriptionProjectTypeList) == 0) {
                $project_ctn += 1;
                $project_price += $item['price'];
            }
        }

        // 匹配需求-拿地数量得分
        $land_ctn_score = $land_ctn * 5 < 30 ? $land_ctn * 5 : 30;
        // 匹配需求-拿地金额得分
        $land_price_score = floor($land_price / 1000) < 30 ? floor($land_price / 1000) : 30;
        // 匹配需求-在建项目数量得分
        $project_ctn_score = $project_ctn * 5 < 30 ? $project_ctn * 5 : 30;
        // 匹配需求-在建项目投资得分
        $project_price_score = floor($project_price / 1000) < 30 ? floor($project_price / 1000) : 30;
        // 匹配需求模块得分
        $matchRequirementModuleScore = ($land_ctn_score + $land_price_score + $project_ctn_score + $project_price_score) * 0.3;
        // 开发商总得分（得分区间为0-100分，大于100按100分计算）
        $developer_score = $investModuleScore + $recoveriesModuleScore + $creditModuleScore + $annualIncreaseModuleScore + $matchRequirementModuleScore;
        if ($developer_score > 100) {
            $developer_score = 100;
        }
        if ($developer_score < 0) {
            $developer_score = 0;
        }

        return [
            "developer_score" => round($developer_score, 2),
            "match_requirement_module_score" => round($matchRequirementModuleScore, 2),
            "match_requirement_land_ctn" => $land_ctn,
            "match_requirement_project_ctn" => $project_ctn,
        ];
    }

    private function getAnalyze($keyword)
    {
        $esCommand = new Command();
        $esCommand->db = \Yii::$app->get('elasticsearch');
        $esCommand->index = BigDataCustomerModel::index();
        $esCommand->type = BigDataCustomerModel::type();
        $condition = [
            'text' => $keyword,
            "analyzer" => 'ik_smart'
        ];
        $urls = [];
        $urls[] = BigDataCustomerModel::index();
        $urls[] = '_analyze';
        $str = json_encode($condition, JSON_UNESCAPED_UNICODE);
        $analyzeList = $esCommand->db->get($urls, [], $str);

        $subWords = [];
        if (!empty($analyzeList) && !empty($analyzeList['tokens'])) {
            $highFreWordService = new HighFrequencyWordService();
            $list = $highFreWordService->getList();
            foreach ($analyzeList['tokens'] as $key => $token) {
                if (!in_array($token['token'], $list)) {
                    $subWords[] = $token['token'];
                }
            }
        }
        return $subWords;
    }
}